package org.test.java;

import static org.test.java.ShuaTa.httpRequestWithLogFile;
import static org.test.java.ShuaTa.judgeChips;
import static org.test.java.ShuaTa.judgeTili;
import static org.test.java.ShuaTa.print;
import static org.test.java.ShuaTa.sleepTime;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class TanSuo implements Runnable {
	private String _sid;
	Properties props;
	private String mapStageDetailId = "39";
	private static String logFile = "tansuo.log";

	public TanSuo(String _sid, Properties props) {
		this._sid = _sid;
		this.props = props;
		if (props.containsKey("MapStageDetailId")) {
			mapStageDetailId = props.getProperty("MapStageDetailId");
		}
		if (props.containsKey("tanSuoLogFile")) {
			logFile  = props.getProperty("tanSuoLogFile");
		}
		if (props.containsKey("shuaTaSleepTime")) {
			sleepTime = Integer.parseInt(props.getProperty("shuaTaSleepTime"));
		}
	}

	@Override
	public void run() {
		int temp = 0;
		while (true) {
			try {
				try {
					if (temp >= 1)
						Thread.sleep(sleepTime * 60 * 1000);
					temp++;
				} catch (InterruptedException e1) {
					e1.printStackTrace();
					try {
						log(e1.getMessage());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				try {
					if (judgeTili(_sid, 50, logFile)
							|| (judgeChips(_sid, 1, logFile) && judgeTili(_sid, App.energyControl, logFile))) {
						Map map = httpRequestWithLogFile(_sid, "mapstage.php",
								"GetUserMapStages", "", logFile);
						if(getInt(map, "status") != 1)
							continue;
						Map data = (Map)map.get("data");
						int maxStageId = 0;
						for(Object key : data.keySet()){
							int stageId = Integer.parseInt(key.toString());
							if(getInt((Map)data.get(key), "FinishedStage")==3){
								maxStageId = Math.max(maxStageId, stageId);
							}
						}
						System.out.println(maxStageId);
						Object obj = httpRequestWithLogFile(_sid, "mapstage.php",
								"Explore", "MapStageDetailId="
										+ maxStageId, logFile);
						log("探索结果:" + obj);
					} else {
						log("体力不够，等待探索。");
					}
				} catch (Exception e) {
					e.printStackTrace();
					try {
						log(e.getMessage());
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private int getInt(Map map, String key) {
		return (Double.valueOf(map.get(key).toString())).intValue();
	}

	private void log(String message) throws IOException {
		print(logFile, message);
	}

}
